﻿using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Smo;

namespace CoNatural.Data.VisualStudio.AddIn.Helpers {
	public class PropertyHelper {
		static public CoNatural.Data.Helpers.PropertyHelper CreatePropertyHelper(Database database, string name, DataType dataType, bool isNullable, ParameterDirection direction) {
			string sqlDbTypeName = Enum.GetName(typeof(SqlDataType), dataType.SqlDataType);
			string udtTypeName = string.Empty;

			// handle user defined data types
			if (dataType.SqlDataType == SqlDataType.UserDefinedDataType) {
				try {
					UserDefinedDataType udt = database.UserDefinedDataTypes[dataType.Name];
					sqlDbTypeName = udt.SystemType;
					dataType = new DataType(udt);
				}
				catch {
					/* unsupported type name, the command won't compile */
					sqlDbTypeName = SqlDbType.Int.ToString();
				}
			}

			// simplify type
			switch (dataType.SqlDataType) {
				case SqlDataType.NVarCharMax:
				case SqlDataType.SysName:
				case SqlDataType.VarCharMax:
					sqlDbTypeName = SqlDbType.NVarChar.ToString();
					break;

				case SqlDataType.VarBinaryMax:
					sqlDbTypeName = SqlDbType.VarBinary.ToString();
					break;

				case SqlDataType.Numeric:
					sqlDbTypeName = SqlDbType.Decimal.ToString();
					break;

				case SqlDataType.HierarchyId:
				case SqlDataType.Geography:
				case SqlDataType.Geometry:
					sqlDbTypeName = SqlDbType.Udt.ToString();
					udtTypeName = dataType.SqlDataType.ToString();
					break;
			}

			// create SqlParameter
			name = name.Replace(" ", "_");
			SqlDbType sqlDbType = (SqlDbType)Enum.Parse(typeof(SqlDbType), sqlDbTypeName, true);
			SqlParameter sqlParameter = new SqlParameter(name, sqlDbType, dataType.MaximumLength);
			sqlParameter.IsNullable = isNullable;
			sqlParameter.Direction = direction;
			sqlParameter.Precision = (byte)dataType.NumericPrecision;
			sqlParameter.Scale = (byte)dataType.NumericScale;
			sqlParameter.UdtTypeName = udtTypeName;

			return new CoNatural.Data.Helpers.PropertyHelper(sqlParameter);
		}
	}
}
